package utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * doc文档替换工具
 */
public class WordDocReplaceUtils {

    private static final Logger log = LoggerFactory.getLogger(WordDocReplaceUtils.class);

    /**
     * doc文档替换 (apache poi)
     * @param templateFilePath 模板路径
     * @param outFilePath 输出路径
     * @param map 替换参数 (key: ${data.xxx})
     */
    public static void docxReplace(String templateFilePath,String outFilePath, Map<String, String> map){
        File file = new File(templateFilePath);
        if (!file.exists()){
            log.error("替换文件失败，文件不存在");
            return;
        }

        HWPFDocument document = null;
        try {
            document = new HWPFDocument(new FileInputStream(templateFilePath));
            Range range = document.getRange();

            for (Map.Entry<String, String> entry : map.entrySet()) {
                range.replaceText(entry.getKey(), entry.getValue());
            }

            // 创建新文件存放新内容
            FileOutputStream outStream = new FileOutputStream(outFilePath);
            document.write(outStream);
            outStream.close();

        } catch (IOException e) {
            log.error("替换word里面的内容出错-{}", e);
        }

    }

}
